package me.thinkjet.sso.server.ticket;

import me.thinkjet.sso.server.authentication.Authentication;

/**
 * 
 * @ClassName ServiceTicket
 * @author johnny_zyc
 * @Modified 2013-3-2 下午2:48:51
 * 
 */
public final class ServiceTicket extends AbstractTicket {
	public static String PREFIX = "ST";
	
	public final static String TICKET_NAME = "ticket";

	private static long EXPIRED_TIME = 30;

	private static final long serialVersionUID = -4223319704861765405L;

	private String service;

	private boolean fromNewLogin;

	private Boolean grantedTicketAlready = false;

	public ServiceTicket() {
	}

	protected ServiceTicket(final String id, final TicketGrantingTicket ticket,
			final String service, final boolean fromNewLogin) {
		super(id, ticket);

		this.service = service;
		this.fromNewLogin = fromNewLogin;
	}

	public boolean isFromNewLogin() {
		return this.fromNewLogin;
	}

	public String getService() {
		return this.service;
	}

	public TicketGrantingTicket grantTicketGrantingTicket(final String id,
			final Authentication authentication) {
		synchronized (this) {
			if (this.grantedTicketAlready) {
				throw new IllegalStateException(
						"TicketGrantingTicket already generated for this ServiceTicket.  Cannot grant more than one TGT for ServiceTicket");
			}
			this.grantedTicketAlready = true;
		}

		return new TicketGrantingTicket(id, this.getGrantingTicket(),
				authentication, false);
	}

	public Authentication getAuthentication() {
		return null;
	}

	@Override
	public boolean isExpired() {
		return System.currentTimeMillis() - this.getLastTimeUsed() > ServiceTicket.EXPIRED_TIME * 1000
				|| this.getGrantingTicket().isExpired() || isExpiredInternal();
	}
}
